<?php

session_start();

require_once '../common/conn.php';
require_once '../common/function.php';
require_once '../db/admin.db.php';

$action = $_POST['action'];

switch ($action) {
    case 'login':
        login();
        break;
    case 'logout':
        logout();
        break;
    default:
        $res['code'] = 2;
        $res['msg'] = '申请类型错误';
}

/**
 * 登录
 */
function login() {
    $accountId = isset($_POST['username']) ? addslashes(trim($_POST['username'])) : "";
    $accountPass = isset($_POST['password']) ? strtoupper(md5(trim($_POST['password']))) : "";

    $dbc = new DBC();
    $adminDb = new AdminDb($dbc);
    $user = $adminDb->getAccount($accountId, $accountPass);
    $dbc->close();
    if (isArrayNotEmpty($user)) {
        $_SESSION['AdminId'] = $user[0]['id_x'];
        $_SESSION['AdminName'] = $user[0]['Admin'];
        echo "<script type='text/javascript'>location.href='../main.php'</script>";
    } else {
        echo "<script type='text/javascript'>location.href='../admin.php'</script>";
    }
    exit;
}

/**
 * 退出登录
 */
function logout() {
    $username = isset($_POST['username']) ? addslashes(trim($_POST['username'])) : "username";
    $accountId = isset($_SESSION['AdminId']) ? addslashes(trim($_SESSION['AdminId'])) : "AdminId";
    if ($accountId == $username) {
        unset($_SESSION['AdminId']);
    }
    echo "<script type='text/javascript'>location.href='../admin.php'</script>";
    exit;
}
